<script setup>
import {onMounted, ref} from "vue";
import {ElMessage, ElMessageBox, ElTable} from 'element-plus';
import { format } from 'date-fns'; // 引入 date-fns 库用于格式化日期
import axios from "axios";
import Audio from "@/components/home/right/audio_MD/Audio.vue";
let input1 = ref("");
let input2 = ref("");
let consultantOptions = ref([]);//咨询师列表
let selectedRowIds = ref([]); // 存储用户选择的行的 ID
// 处理选择框变化
const handleSelectionChange = (selection) => {
  selectedRowIds.value = selection.map(row => row.announcementId);
};

let tableData = ref([]);
let centerDialogVisible = ref(false);
//弹框修改显示的值
let from = ref({
  announcementId:null,
  title:'',
  content:'',
  consultantId:null,
  consultantName:'',
  consultantRealname:'',
  consultantAvatar:'',
  levelId:null,
  pubishTime:''

});


// 批量删除操作
const batchDeleteRows = () => {
  if (selectedRowIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据进行删除');
    return;
  }

  ElMessageBox.confirm(
      '确定要删除选中的公告吗？',
      '批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      const response = await axios.delete("/announcement/batch", {
        data: selectedRowIds.value
      });
      if (response.data) {
        ElMessage({
          type: 'success',
          message: '删除成功'
        });
        refreshTableData();
        selectedRowIds.value = []; // 清空已删除的 ID 列表
      } else {
        ElMessage.error('删除失败，请稍后再试');
      }
    } catch (error) {
      console.error(error);
      ElMessage.error('删除过程中发生错误');
    }
  }).catch(() => {
    ElMessage.info('已取消删除');
  });
};
// 添加数据
const addRow = () => {
  centerDialogVisible.value = true;
  // 重置表单数据
  from.value = {
    announcementId: null,
    title: '',
    content: '',
    consultantId: null,
    consultantName: '',
    consultantRealname: '',
    consultantAvatar: '',
    levelId: null,
    publishTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss') // 设置
  };
};
// 获取咨询师列表
const getConsultantOptions = () => {
  axios.get("/consultant/findAllConsultant2") // 假设这是获取咨询师的 API
      .then((resp) => {
        consultantOptions.value = resp.data.data;
        console.log("咨询师列表数据");
        console.log(resp.data.data);
      })
      .catch((err) => {
        ElMessage.error("获取咨询师失败：" + err.message);
      });
};


// 获取表格数据的函数
const refreshTableData = () => {
  axios.get("/announcement/list")
      .then((resp) => {
        tableData.value = resp.data;
        console.log("这是总的数据信息");
        console.log(tableData.value);
      })
      .catch((err) => {
        console.error(err);
      });
};

const onConsultantChange = (newValue) => {
  const selectedConsultant = consultantOptions.value.find(consultant => consultant.username === newValue);
  if (selectedConsultant) {
    from.value.consultantId = selectedConsultant.consultantId;
    from.value.consultantRealname = selectedConsultant.realname;
    from.value.consultantAvatar = selectedConsultant.avatar;
  }
};
// 刷新页面
onMounted(() => {
  refreshTableData();
  getConsultantOptions();
});


// 模糊查询
const searchAnnouncement = () => {
  axios.get("/announcement/list", {
    params: {
      title: input1.value,
      consultantRealname: input2.value,
    }
  })
      .then((resp) => {
        tableData.value = resp.data;
        console.log("查询结果：", tableData.value);
      })
      .catch((err) => {
        console.error("查询失败：", err);
      });
};



// 重置搜索框并刷新表格数据
const resetSearch = () => {
  input1.value = '';
  input2.value = '';
  refreshTableData(); // 调用刷新表格数据的方法
};

//删除这一条数据
const deleteRow = (id) => {
  console.log("delete...", id);
  axios.delete(`/announcement?id=${id}`)
      .then((resp) => {
        console.log(resp);
        refreshTableData();
        // 重新获取数据或更新tableData
      })
      .catch((err) => {
        console.log(axios.delete(`/announcement/${id}`));
        console.log(err);
      });
};

// 点击修改按钮后，更新from为该行数据
const updateRow = (row) => {
  centerDialogVisible.value = true;
  from.value = {
    announcementId: row.announcementId,
    title: row.title,
    content: row.content,
    consultantId: row.consultant.consultantId,
    consultantName: row.consultant.username,
    consultantRealname: row.consultant.realname,
    consultantAvatar: row.consultant.avatar,
    publishTime: row.publishTime,
  };
  console.log("这是修改后的值")
  console.log(from.value);
};

const confirm = async () => {
  // if (!from.value.title || !from.value.content || !from.value.consultantId) {
  //   ElMessage.error('请填写所有必填项');
  //   return;
  // }

  console.log("确认操作...");
  console.log(from.value);

  try {
    let response;

    if (from.value.announcementId) {
      // 修改操作
      // 确保 uploadTime 是 Date 对象
      if (typeof from.value.pubishTime === 'string') {
        from.value.pubishTime = new Date(from.value.pubishTime);
      }
      response = await axios.put("/announcement", {
        announcementId: from.value.announcementId,
        title: from.value.title,
        content: from.value.content,
        consultantId: from.value.consultantId,
        publishTime: from.value.pubishTime
          });
    } else {
      // 添加操作
      response = await axios.post("/announcement", {
        title: from.value.title,
        content: from.value.content,
        consultantId: from.value.consultantId,
        publishTime: format(new Date(), 'yyyy-MM-dd HH:mm:ss'), // 设置为当前时间
      });
    }

    if (response.data) {
      ElMessage({
        type: 'success',
        message: '操作成功'
      });
      refreshTableData();
      centerDialogVisible.value = false;
    } else {
      ElMessage({
        type: 'error',
        message: '操作失败，请稍后再试'
      });
    }
  } catch (error) {
    console.error(error);
    if (error.response) {
      ElMessage.error(`操作过程中发生错误: ${error.response.data.message || error.response.statusText}`);
    } else if (error.request) {
      ElMessage.error('未接收到响应，请检查网络连接');
    } else {
      console.log(from.value)
      ElMessage.error('请求设置错误，请检查代码');
    }
  }
};


const showFullContent = (content) => {
  // 确保 content 是一个有效的字符串
  if (typeof content !== 'string') {
    content = "公告内容为空或格式不正确";
  }

  ElMessageBox.alert(content, '公告内容', {
    dangerouslyUseHTMLString: true,
    showConfirmButton: false,
    showClose: true,
    customClass: 'announcement-full-content-dialog'
  }).catch((error) => {
    console.error("显示公告内容时发生错误:", error);
  });
};
</script>

<template>
  <!--搜索框-->
  <div class="title">
    标题
    <el-input v-model="input1" style="width: 240px" placeholder="Please input" />
    咨询师姓名
    <el-input v-model="input2" style="width: 240px" placeholder="Please input" />
    <el-button type="success" class="search" @click="searchAnnouncement">搜索</el-button>
    <el-button type="warning" @click="resetSearch">重置</el-button>
  </div>
  <!--    添加和批量删除按钮-->
  <div class="addbtn">
    <el-button type="success" @click="addRow">添加</el-button>
    <el-button type="danger" @click="batchDeleteRows">批量删除</el-button>
  </div>


  <!-- 表格 -->
  <div class="table">
    <el-table :data="tableData" style="width: 90%" height="600" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column property="announcementId" label="公告编号" width="120"/>
      <el-table-column property="title" label="标题" width="120" />
      <el-table-column property="content" label="公告内容" width="300">
        <template #default="scope">
          <div class="announcement-content" @dblclick="showFullContent(scope.row.content)">
            {{ scope.row.content }}
          </div>
        </template>
      </el-table-column>
      <el-table-column property="consultant.username" label="咨询师用户名" width="120" />
      <el-table-column property="consultant.realname" label="咨询师名字" width="120" />
      <el-table-column label="咨询师头像" width="180">
        <template #default="scope">
          <img :src="scope.row.consultant.avatar" style="width: 100px; height: auto;" />
        </template>
      </el-table-column>
      <el-table-column property="publishTime" label="发布时间" width="200" />
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button type="warning" @click="updateRow(scope.row)">修改</el-button>
          <el-button type="danger" @click="deleteRow(scope.row.announcementId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>

  <!--  弹窗的对话框-->
  <!--  弹窗的对话框-->
  <div>
    <el-dialog v-model="centerDialogVisible" title="添加新公告" width="500" center>
      <div class="content">
        <div> 公告标题 <el-input v-model="from.title" style="width: 240px" placeholder="Please input" /></div>
        <div> 公告内容  <el-input v-model="from.content" style="width: 240px" placeholder="Please input" /></div>
        <div> 咨询师用户名
          <el-select v-model="from.consultantName" placeholder="请选择咨询师" style="width: 240px" @change="onConsultantChange">
            <el-option
                v-for="item in consultantOptions"
                :key="item.username"
                :label="item.username"
                :value="item.username">
            </el-option>
          </el-select>
        </div>
        <div> 咨询师姓名  <el-input v-model="from.consultantRealname" style="width: 240px" placeholder="Please input" readonly /></div>
        <div> 咨询师头像
          <img :src="from.consultantAvatar" style="width: 100px; height: auto;" />
        </div>
        <!-- 发布时间在添加时自动设置，修改时不显示 -->
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.title{
  margin-top: 20px;
  margin-left: 20px;
}
.search{
  margin-left: 10px;
}
.addbtn{
  margin: 30px;

}
.table{
  margin-left: 50px;
}
.content>div{
  margin-top: 20px;
  margin-left: 30px;
}
.announcement-content {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 3; /* 限制显示3行 */
  overflow: hidden;
  text-overflow: ellipsis;
  cursor: pointer; /* 添加鼠标指针样式，提示可以点击 */
}
.announcement-full-content-dialog .el-message-box__content {
  white-space: pre-wrap; /* 保留空白符和换行符 */
  word-break: break-word; /* 防止单词溢出 */
}
</style>